
//
//  AFNNetWorkManager.m
//  zjsapp
//
//  Created by 技术部mac1 on 2018/1/4.
//  Copyright © 2018年 njmd. All rights reserved.
//

#import "AFNNetWorkManager.h"
#import "UserInfo.h"
#import "LoginViewController.h"
@implementation AFNNetWorkManager

+(instancetype)shareAFNNetWorkManager{
    
    static AFNNetWorkManager *shareAFNNetWorkManager=nil;
    if (shareAFNNetWorkManager == nil) {
        static dispatch_once_t onceToken;
        dispatch_once(&onceToken, ^{
            shareAFNNetWorkManager = [[AFNNetWorkManager alloc]init];
        });
    }
    return shareAFNNetWorkManager;
}

- (NSURLSessionDataTask *)basePost:(NSString *)URLString
                            domain:(NSString *)domain
                reqeusetSerializer:(AFHTTPRequestSerializer<AFURLRequestSerialization> *)requestSerializer
                        parameters:(id)parameters
                           success:(void (^)(NSURLSessionDataTask *, Result *))success
                           failure:(void (^)(NSURLSessionDataTask *, NSError *))failure {
    NSMutableString *url = [NSMutableString stringWithFormat:@"%@%@?",domain,URLString];
    AFHTTPSessionManager *sessionManager = [AFHTTPSessionManager manager];
    sessionManager.requestSerializer  = requestSerializer;
    sessionManager.responseSerializer = [AFJSONResponseSerializer serializer];
    sessionManager.responseSerializer.acceptableContentTypes = [NSSet setWithObjects:@"application/json", @"text/json", @"text/javascript",@"text/plain",@"text/html", nil];
    sessionManager.requestSerializer.timeoutInterval = 15.0f;
    [self addRequestHeaders:sessionManager];
    NSURLSessionDataTask *dataTask = [sessionManager POST:[url stringByAddingPercentEncodingWithAllowedCharacters:[NSCharacterSet URLQueryAllowedCharacterSet]]
                                               parameters:parameters
                                                  headers:nil
                                                 progress:nil
                                                  success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        Result *result = nil;
        if(responseObject && [responseObject isKindOfClass:[NSDictionary class]]) {
            result = [Result mj_objectWithKeyValues:responseObject];
        }
        if (result.code == 10001) {
            [MBProgressHUD showTextHUD:result.msg];
            [self tokenExpired];
        }else{
            success(task,result);
        }
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        if (failure) {
            failure(task,error);
        }
    }];
    
    [dataTask resume];
    return dataTask;
}

- (NSURLSessionDataTask *)Post:(NSString *)URLString
  parameters:( id)parameters
     success:( void (^)(NSURLSessionDataTask *task, Result *result))success
     failure:( void (^)(NSURLSessionDataTask *  task, NSError *error))failure
    
{
    return  [self basePost:URLString
            domain:[self checkURL]
reqeusetSerializer:[AFHTTPRequestSerializer serializer]
        parameters:parameters
           success:success
           failure:failure];
}

- (NSURLSessionDataTask *)postJson:(NSString *)URLString
                        parameters:(id)parameters
                           success:(void (^)(NSURLSessionDataTask *, Result *))success
                           failure:(void (^)(NSURLSessionDataTask *, NSError *))failure {
    return  [self basePost:URLString
                domain:[self checkURL]
    reqeusetSerializer:[AFJSONRequestSerializer serializer]
            parameters:parameters
               success:success
               failure:failure];
}

- (NSURLSessionDataTask *)getWithDomain:(NSString *)DomainString
                                     url:(NSString *)URLString
                              parameters:( id)parameters
                                 success:( void (^)(NSURLSessionDataTask *task, Result *result))success
                                 failure:( void (^)(NSURLSessionDataTask *  task, NSError *error))failure
{
    NSMutableString *url = [NSMutableString stringWithFormat:@"%@%@?",DomainString,URLString];
    AFHTTPSessionManager *sessionManager = [ZJSAFmanager shareManager]  ;
    sessionManager.responseSerializer = [AFJSONResponseSerializer serializer];
    sessionManager.responseSerializer.acceptableContentTypes = [NSSet setWithObjects:@"application/json", @"text/json", @"text/javascript",@"text/plain",@"text/html", nil];
    sessionManager.requestSerializer.timeoutInterval = 15.0f;
    [self addRequestHeaders:sessionManager];
    NSURLSessionDataTask *dataTask = [sessionManager GET:[url stringByAddingPercentEncodingWithAllowedCharacters:[NSCharacterSet URLQueryAllowedCharacterSet]] parameters:parameters  headers:nil progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        Result *result = nil;
        if(responseObject && [responseObject isKindOfClass:[NSDictionary class]]) {
            result = [Result mj_objectWithKeyValues:responseObject];
        }
        if (result.code == 10001) {
            [MBProgressHUD showTextHUD:result.msg];
            [self tokenExpired];
        }else{
            success(task,result);
        }
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        
        if (failure) {
            failure(task,error);
        }
        
    }];
    [dataTask resume];
    return dataTask ;
}

- (NSURLSessionDataTask *)Get:(NSString *)URLString
                   parameters:( id)parameters
                      success:( void (^)(NSURLSessionDataTask *task, Result *result))success
                      failure:( void (^)(NSURLSessionDataTask *  task, NSError *error))failure
{
    return  [self getWithDomain:[self checkURL] url:URLString parameters:parameters success:success failure:failure];
}


- (void)addRequestHeaders:(AFHTTPSessionManager *)sessionManager {
    id userInfoString =  [[NSUserDefaults standardUserDefaults] objectForKey:KUserInfo];
    if (!userInfoString) {
        return;
    }
    UserInfo *userInfo = [UserInfo mj_objectWithKeyValues:userInfoString];
    [sessionManager.requestSerializer setValue:[NSString stringWithFormat:@"appToken=%@", userInfo.token]  forHTTPHeaderField:@"Cookie"];
    //添加请求头
//    [sessionManager.requestSerializer setValue:kParamCallSourceStr forHTTPHeaderField:kRequestCallSource];
//    [sessionManager.requestSerializer setValue:[[GlobalVar sharedInstance] userToken] forHTTPHeaderField:Token];
//    [sessionManager.requestSerializer setValue:[getUUID getDeviceID] forHTTPHeaderField:@"DEVICE-ID"];

}

- (void)tokenExpired {
    [[NSUserDefaults standardUserDefaults] removeObjectForKey:KUserInfo];
    [[NSUserDefaults standardUserDefaults] synchronize];
    [[NSNotificationCenter defaultCenter] postNotificationName:NotifcationName_LoginOutSuccess object:nil];
    [[NSNotificationCenter defaultCenter] postNotificationName:NotifcationName_foodExpairChange object:nil];
}

- (NSString *)checkURL{
    NSString *urlString = @"http://120.55.103.206:8010";
    return urlString;
}



@end
